#!/bin/bash

echo "==================================================================="
echo "后续功能改进测试"
echo "==================================================================="
echo ""

# 测试计数器
total_tests=0
passed_tests=0
failed_tests=0

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 测试函数
test_case() {
    local test_name="$1"
    local command="$2"
    local expected_in_output="$3"
    
    total_tests=$((total_tests + 1))
    echo "测试 $total_tests: $test_name"
    
    output=$($command 2>&1)
    
    if echo "$output" | grep -q "$expected_in_output"; then
        echo -e "  ${GREEN}✓ 通过${NC}"
        passed_tests=$((passed_tests + 1))
    else
        echo -e "  ${RED}✗ 失败${NC}"
        echo "  期望包含: $expected_in_output"
        echo "  实际输出前100字符: ${output:0:100}"
        failed_tests=$((failed_tests + 1))
    fi
    echo ""
}

echo "===================== DOT格式导出功能测试 ====================="
echo ""

# 测试1: 基本DOT导出
test_case "基本DOT导出" \
    "./moparse -i test_connection.modb -m top_module --export-dot test_dot_basic.dot" \
    "Successfully exported to DOT format"

# 测试2: 验证DOT文件包含正确的图声明
test_case "DOT文件包含digraph声明" \
    "cat test_dot_basic.dot" \
    "digraph"

# 测试3: 验证DOT文件包含节点
test_case "DOT文件包含子模块节点" \
    "cat test_dot_basic.dot" \
    "u_sub_a"

# 测试4: 验证DOT文件包含连接
test_case "DOT文件包含连接边" \
    "cat test_dot_basic.dot" \
    "top_module"

# 测试5: 带子模块过滤的DOT导出
test_case "带子模块过滤的DOT导出" \
    "./moparse -i test_pipeline.modb -m top_module --export-dot test_dot_filtered.dot -sf u_sub_c" \
    "Successfully exported"

# 测试6: 验证过滤后只包含指定子模块
test_case "验证DOT文件包含u_sub_c" \
    "cat test_dot_filtered.dot" \
    "u_sub_c"

# 测试7: 生成PNG图片（如果有dot命令）
if command -v dot &> /dev/null; then
    test_case "生成PNG图片" \
        "dot -Tpng test_dot_basic.dot -o test_dot_basic.png 2>&1 && ls test_dot_basic.png" \
        "test_dot_basic.png"
else
    echo "跳过PNG生成测试（未安装graphviz）"
fi

# 测试8: 流水线模块完整导出
test_case "流水线模块完整DOT导出" \
    "./moparse -i test_pipeline.modb -m top_module --export-dot test_pipeline_full.dot" \
    "Successfully exported"

# 测试9: 验证包含所有3个子模块
test_case "验证包含所有3个子模块" \
    "cat test_pipeline_full.dot" \
    "u_sub_a"

echo "==================================================================="
echo "测试结果总结"
echo "==================================================================="
echo "总测试数: $total_tests"
echo -e "通过: ${GREEN}$passed_tests${NC}"
echo -e "失败: ${RED}$failed_tests${NC}"
echo ""

if [ $failed_tests -eq 0 ]; then
    echo -e "${GREEN}🎉 所有测试通过！${NC}"
    exit 0
else
    echo -e "${RED}❌ 有测试失败，请检查！${NC}"
    exit 1
fi
